﻿var map;
var myLocation;
var mid = 1;
var infoWindow;
var geocoder;
var markersArray = [];
var rspanel = "";
var emptyJson = {};
var TK = {};

//////////////////////////////////////////////////////
function tam(ID_DichVu) {
    return "<strong>List Point: </strong></br>" +
    '<div>' +
        '<table style="width: 100%; height: 27px;">' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Service: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<select ID="List" style="width: 90%" onchange="selectedChange()" > ' + a(ID_DichVu) +
                    '</select>' +
                '</td>' +
               '</tr>' +
        '</table>' +
        '<div id=rspanel>' +
        '</div>' +
    '</div>';
}


//////////////////////////////////////////////////////
function b(diadiem) {
    return '<div>' +
        '<table style="width: 300px; height: 27px;">' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Service: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<select ID="List1" style="width: 90%"onchange="Change()"  onclick="select_onclick()" >' + a(diadiem.ID_DichVu) +
                    '</select>' +
                '</td>' +
            '</tr>' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Point Name: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<input name="Name" ID="PointName" type="text"  value=' + diadiem.TenDiaDiem + ' style="width: 90%"/>' +
                '</td>' +
            '</tr>' +
        '</table>' +
    '</div>';
}


//////////////////////////////////////////////////////
function a(ID_DichVu) {
    var res = "";
    $.ajax({
        cache: false,
        async: false,
        url: "http://localhost:8989/Map/getAllDV",
        type: "Get",
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                if (data[i].ID == ID_DichVu)
                    res += '<option selected="true" value=' + data[i].ID + '>' + data[i].TenDichVu + '</option>';
                if (data[i].ID != ID_DichVu)
                    res += '<option value=' + data[i].ID + '>' + data[i].TenDichVu + '</option>';
            }
        },
        error: function () {
            alert('Failure ');
        }
    });
    return res;
}


//////////////////////////////////////////////////////
function select_onclick() {
    var b = a();
}


//////////////////////////////////////////////////////
function Change() {

}


//////////////////////////////////////////////////////
$(document).ready(function () {
    $("select #List1").click(function () {
//        alert("Tim Duoc");
    });
});

//////////////////////////////////////////////////////
//Dùng để hiển thị trong InfoEditWindow...
//////////////////////////////////////////////////////
var headHTML = '<div>' +
        '<table style="width: 300px; height: 27px;">' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Service: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<select ID="List1" style="width: 90%"onchange="Change()"  onclick="select_onclick()" >' + a(1) +
                    '</select>' +
                '</td>' +
            '</tr>' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Point Name: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<input name="Name" ID="PointName" type="text"  value="ASDF" style="width: 90%"/>' +
                '</td>' +
            '</tr>' +
        '</table>' +
    '</div>';

//////////////////////////////////////////////////////
var tailHTML = '<div>' +
        '<table style="width: 300px; height: 27px;">' +
            '<tr>' +
                '<td class="style1" style="width: 20%" align="center">' +
                    '<a href="#" onclick="AddPoint();">Save</a>' +
                '</td>' +
                '<td class="style1" style="width: 20%" align="center">' +
                    '<a href="#" onclick="DelPoint();">Delete</a>' +
                '</td>' +
                '<td class="style1" style="width: 20%" align="center">' +
                     '<a href="#" onclick="UpdatePoint();">Update</a>' +
                '</td>' +
                '<td class="style1" style="width: 40%" align="certer">' +
                    '<a href="#" id="SearchNearby" onclick="SearchNearby();">Search Nearby</a>' +
                '</td>' +
            '</tr>' +
        '</table>' +
    '</div>';

//////////////////////////////////////////////////////
var addHTML = '<div>' +
        '<table style="width: 300px; height: 27px;">' +
            '<tr>' +
                '<td class="style1" style="width: 20%" align="center">' +
                    '<a href="#" onclick="AddPoint();">Save</a>' +
                '</td>' +
            '</tr>' +
        '</table>' +
    '</div>';


//////////////////////////////////////////////////////
//Hàm thêm địa điểm...
//////////////////////////////////////////////////////
function AddPoint() {
    if (TK.ID == null) {
        alert("Vui Long Dang Nhap");
        return;
    }
    var tk = {};
    tk.TenDiaDiem = document.getElementById('PointName').value;
    tk.ID_TaiKhoan = TK.ID;
    tk.ID_DichVu = document.getElementById('List1').value;
    tk.ViDo = document.getElementById('Lat').value;
    tk.TungDo = document.getElementById('Lng').value;
    tk.GhiChu = "ABC"
    $.ajax({
        cache: false,
        async: false,
        url: "http://localhost:8989/Map/DiaDiem",
        type: "POST",
        data: JSON.stringify(tk),
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (data) {
            alert("Successful");
        },
        error: function () {
            alert('Failure ');
        }
    });

    loadLeftMenu(tk.ID_DichVu);
}


//////////////////////////////////////////////////////
// Hàm xóa địa điểm...
//////////////////////////////////////////////////////
function DelPoint(link) {
    $.ajax({
        url: "http://localhost:8989/Map/DiaDiem?ID= " + link.name,
        type: "Delete",
        success: function (data) {
            alert("Successful");
        },
        error: function () {
            alert('Failure ');
        }
    });
    loadLeftMenu(document.getElementById('List1').value);
}


//////////////////////////////////////////////////////
// Hàm update địa điểm...
//////////////////////////////////////////////////////
function UpdatePoint(link) {
    var tk = {};
    tk.ID = link.name;
    tk.TenDiaDiem = document.getElementById('PointName').value;
    tk.ID_TaiKhoan = TK.ID;
    tk.ID_DichVu = document.getElementById('List1').value;
    tk.ViDo = document.getElementById('Lat').value;
    tk.TungDo = document.getElementById('Lng').value;
    tk.GhiChu = "ABC";
    $.ajax({
        cache: false,
        async: false,
        url: "http://localhost:8989/Map/UpdateDD",
        type: "PUT",
        data: JSON.stringify(tk),
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (data) {
//            alert(data.toString());
        },
        error: function () {
            alert('Failure ');
        }
    });
    loadLeftMenu(document.getElementById('List1').value);
}


//////////////////////////////////////////////////////
//Tìm địa điểm dịch vụ gần nhất...
//////////////////////////////////////////////////////
function SearchNearBy(link) {
    var id_diadiem = link.name;

    $.ajax({
        cache: false,
        async: false,
        url: "http://localhost:8989/Map/SearchNearBy?id_diadiem=" + id_diadiem,
        type: "Get",
        success: function (data) {
            var pos = new google.maps.LatLng(data.ViDo, data.TungDo);
            map.setCenter(pos);
            var marker = new google.maps.Marker({
                map: map,
                position: pos
            });
            google.maps.event.addListener(marker, 'click', function () {
                ShowEditWindowFull(marker, data);
            });

            google.maps.event.addListener(marker, 'rightclick', function () {
                ShowEditWindowFull(marker, data);
            });
        },
        error: function () {
            alert('Failure ');
        }
    });
}


//////////////////////////////////////////////////////
function initialize() {
    geocoder = new google.maps.Geocoder();

    var myOptions = {
        zoom: 17,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map_canvas'),
            myOptions);



    // Try HTML5 geolocation
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            myLocation = new google.maps.LatLng(position.coords.latitude,
                                             position.coords.longitude);

            map.setCenter(myLocation);
        }, function () {
            handleNoGeolocation(true);
        });
    } else {
        // Browser doesn't support Geolocation
        handleNoGeolocation(false);
    }
    var homeControlDiv = document.createElement('DIV');
    var homeControl = new HomeControl(homeControlDiv, map);

    homeControlDiv.index = 1;
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(homeControlDiv);

    google.maps.event.addListener(map, 'click', function (event) {
        addMarker(event.latLng);
    });
}


//////////////////////////////////////////////////////
function clearOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(null);
        }
    }
}


//////////////////////////////////////////////////////
// Shows any overlays currently in the array...
//////////////////////////////////////////////////////
function showOverlays() {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(map);
        }
    }
}


//////////////////////////////////////////////////////
//Thêm marker vào bản đồ...
//////////////////////////////////////////////////////
function addMarker(location) {
    //tạm thời ẩn các marker khác khi tạo marker mới
    clearOverlays();
    marker = new google.maps.Marker({
        position: location,
        map: map,
        draggable: true,
        animation: google.maps.Animation.DROP
    });
    markersArray.push(marker);
    //    map.setCenter(location);
    for (i in markersArray) {
        google.maps.event.addListener(markersArray[i], 'click', function () {
            ShowInfoWindow(markersArray[i]);
        });
        google.maps.event.addListener(markersArray[i], 'rightclick', function () {
            ShowEditWindow(markersArray[i]);
        });
    }
}


//////////////////////////////////////////////////////
// Sự kiện  click nút Manage Point...
//////////////////////////////////////////////////////
function btnManage_Click() {
    if (TK.ID == null) {
        alert("Ban Chua Dang Nhap");
        return;
    }
    loadLeftMenu(1);
}


//////////////////////////////////////////////////////
// Hiển thị danh sách địa điểm đã lưu...
//////////////////////////////////////////////////////
function loadLeftMenu(ID_DichVu) {
    var panel = document.getElementById('diadiempanel');
    panel.innerHTML = tam(ID_DichVu);
    var id_user = TK.ID;

    var a = document.getElementById("rspanel");
    a.innerHTML = getDSdiadiemfromDV(id_user, ID_DichVu);
}


//////////////////////////////////////////////////////
function selectedChange() {
    //lay danh sach dia diem theo loai dich vu show len panelcontent
    var id_user = TK.ID;
    var c = document.getElementById("List").value;
    var a = document.getElementById("rspanel");
    a.innerHTML = getDSdiadiemfromDV(id_user, c);
}


//////////////////////////////////////////////////////
function linkDiaDiem_Click_1(link) {
    var id = link.name;
    $.ajax({
        cache: false,
        async: false,
        url: "http://localhost:8989/Map/getDiaDiemFromID?id_user=" + id,
        type: "Get",
        success: function (data) {
            var pos = new google.maps.LatLng(data.ViDo, data.TungDo);
            map.setCenter(pos);
            var marker = new google.maps.Marker({
                map: map,
                position: pos
            });
            google.maps.event.addListener(marker, 'click', function () {
                ShowEditWindowFull(marker, data);
            });

            google.maps.event.addListener(marker, 'rightclick', function () {
                ShowEditWindowFull(marker, data);
            });
        },
        error: function () {
            alert('Failure ');
        }
    });
}


//////////////////////////////////////////////////////
function getDSdiadiemfromDV(id_user, id_dv) {
    var dsdiadiem = '';
    $.ajax({
        cache: false,
        async: false,
        url: "http://localhost:8989/Map/getDSDiaDiemFromUSerAndDV?id_user=" + id_user + "&id_div=" + id_dv,
        type: "Get",
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                dsdiadiem += '<img id="marker" alt="My Google Map" src="PIC/marker_sprite.png" /><a href="javascript:void(0);" name="' + data[i].ID +
             '"onclick="linkDiaDiem_Click_1(this);">' + data[i].TenDiaDiem + '</a>' + '</br></br>';
            }
        },
        error: function () {
            alert('Failure ');
        }
    });
    return dsdiadiem;
}


//////////////////////////////////////////////////////
//hàm show thông tin marker...
//////////////////////////////////////////////////////
function ShowInfoWindow(marker) {
    infowindow = new google.maps.InfoWindow({
        content: '<div>' +
        '<table style="width: 300px; height: 27px;">' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Latitude: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<label>' + marker.getPosition().lat() + '</label>' +
                '</td>' +
            '</tr>' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Longitude: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<label>' + marker.getPosition().lng() + '</label>' +
                '</td>' +
            '</tr>' +
        '</table>' +
    '</div>'
    });
    infowindow.open(map, marker);
}


//////////////////////////////////////////////////////
//Hiển thị InfoWindow...
//////////////////////////////////////////////////////
function ShowEditWindow(marker) {
    var infowindow = new google.maps.InfoWindow({
        content: headHTML +
        '<div>' +
        '<table style="width: 300px; height: 27px;">' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Latitude: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<input type="text" style="width: 90%" Id="Lat" value="' + marker.getPosition().lat() + '"  />' +
                '</td>' +
            '</tr>' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Longitude: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<input type="text" style="width: 90%" Id="Lng" value="' + marker.getPosition().lng() + '"  />' +
                '</td>' +
            '</tr>' +
        '</table>' +
       '</div>' + addHTML
    });
    infowindow.open(map, marker);
}


//////////////////////////////////////////////////////
// Hiển thị InfoWindow kèm chức năng thêm, xóa, sửa...
//////////////////////////////////////////////////////
function ShowEditWindowFull(marker, data) {
    var head = b(data);
    var str = head +
        '<div>' +
        '<table style="width: 300px; height: 27px;">' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Latitude: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<input type="text" style="width: 90%" Id="Lat" value="' + marker.getPosition().lat() + '"  />' +
                '</td>' +
            '</tr>' +
            '<tr>' +
                '<td class="style1" style="width: 35%" align="left">' +
                    '<label>Longitude: </label>' +
                '</td>' +
                '<td class="style1" style="width: 65%" align="left">' +
                    '<input type="text" style="width: 90%" Id="Lng" value="' + marker.getPosition().lng() + '"  />' +
                '</td>' +
            '</tr>' +
        '</table>' +
       '</div>' +
       '<div>' +
        '<table style="width: 300px; height: 27px;">' +
            '<tr>' +
                '<td class="style1" style="width: 20%" align="center">' +
                    '<a href="#" onclick="AddPoint();">Save</a>' +
                '</td>' +
                '<td class="style1" style="width: 20%" align="center">' +
                   '<a href="javascript:void(0);" name="' + data.ID +
                       '" onclick="DelPoint(this);">Delete</a>' +
                '</td>' +
                '<td class="style1" style="width: 20%" align="center">' +
                  '<a href="javascript:void(0);" name="' + data.ID +
                       '" onclick="UpdatePoint(this);">Update</a>' +
                '</td>' +
                '<td class="style1" style="width: 40%" align="certer">' +
                    '<a href="javascript:void(0);" name="' + data.ID +
                       '" onclick="ShareDiaDiem(this);">Share</a>' +
                '</td>' +
                 '<td class="style1" style="width: 40%" align="certer">' +
                    '<a href="javascript:void(0);" name="' + data.ID +
                       '" onclick="SearchNearBy(this);">SearchNearBy</a>' +
                '</td>' +
            '</tr>' +
        '</table>' +
    '</div>';
    var infowindow = new google.maps.InfoWindow({
        content: str
    });

    infowindow.open(map, marker);

}


//////////////////////////////////////////////////////
// Xử lý sự kiện khi click vào kết quả search...
//////////////////////////////////////////////////////
function linkDiaDiem_Click(link) {
    var DiaDiem = link.name;
    Search(DiaDiem, false);
}


//////////////////////////////////////////////////////
// Xữ lý sự kiện click vào nút search...
//////////////////////////////////////////////////////
function btnDiaDiem_Click() {
    var address = document.getElementById("address").value;
    Search(address, true);
}


//////////////////////////////////////////////////////
//--------hàm search...
//////////////////////////////////////////////////////
function Search(address, flag) {
    clearOverlays();
    if (!geocoder) {
        geocoder = new google.maps.Geocoder();
    }
    var geocoderRequest = { address: address };
    geocoder.geocode(geocoderRequest, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });

            google.maps.event.addListener(marker, 'click', function () {
                ShowInfoWindow(marker);
            });

            google.maps.event.addListener(marker, 'rightclick', function () {
                ShowEditWindow(marker);
            });


            if (flag == true) {
                var panel = document.getElementById('diadiempanel');
                var panelContent = "<strong>Search Results</strong></br>";
                for (var i = 0; i < results.length; i++) {
                    panelContent += '<img id="marker" alt="My Google Map" src="PIC/marker_sprite.png" /><a href="javascript:void(0);" name="' + results[i].formatted_address +
                    '" onclick="linkDiaDiem_Click(this);">' + results[i].formatted_address + '</a>' + '</br></br>';
                }
                panel.innerHTML = panelContent;
            }

        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}


//////////////////////////////////////////////////////
// Hàm kiểm tra tương thích của trình duyệt..
//////////////////////////////////////////////////////
function handleNoGeolocation(errorFlag) {
    if (errorFlag) {
        var content = 'Error: The Geolocation service failed.';
    } else {
        var content = 'Error: Your browser doesn\'t support geolocation.';
    }

    var options = {
        map: map,
        position: new google.maps.LatLng(60, 105),
        content: content
    };

    var infowindow = new google.maps.InfoWindow(options);
    map.setCenter(options.position);
}


/**
* The HomeControl adds a control to the map that simply
* returns the user to Chicago. This constructor takes
* the control DIV as an argument.
*/

function HomeControl(controlDiv, map) {

    // Set CSS styles for the DIV containing the control
    // Setting padding to 5 px will offset the control
    // from the edge of the map
    controlDiv.style.padding = '5px';

    // Set CSS for the control border
    var controlUI = document.createElement('DIV');
    controlUI.style.backgroundColor = 'white';
    controlUI.style.borderStyle = 'solid';
    controlUI.style.borderWidth = '2px';
    controlUI.style.cursor = 'pointer';
    controlUI.style.textAlign = 'center';
    controlUI.title = 'Click to set the map to Home';
    controlDiv.appendChild(controlUI);

    // Set CSS for the control interior
    var controlText = document.createElement('DIV');
    controlText.style.fontFamily = 'Arial,sans-serif';
    controlText.style.fontSize = '12px';
    controlText.style.paddingLeft = '4px';
    controlText.style.paddingRight = '4px';
    controlText.innerHTML = 'Home';
    controlUI.appendChild(controlText);

    // Setup the click event listeners: simply set the map to Chicago
    google.maps.event.addDomListener(controlUI, 'click', function () {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                myLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                map.setCenter(myLocation);
            });
        }
    });
    google.maps.event.addDomListener(window, 'load', initialize);
}


//////////////////////////////////////////////////////
// Các hàm liên quan đến tài khoản.../////////////////
//////////////////////////////////////////////////////

//////////////////////////////////////////////////////
// Đăng nhập...
//////////////////////////////////////////////////////
function btnLogin_Click() {
    var user = document.getElementById("text_user").value;
    var pass = document.getElementById("text_pass").value;
    if (user == "") {
        alert("Ban chua nhap user!...");
        temp = 0;
    }
    else {
        if (pass == "") {
            alert("Ban chua nhap pass!...");
            temp = 0;
        }
        else {
            // Viết hàm đăng nhập...
            $.ajax({
                url: "http://localhost:8989/Map/TK?user_name=" + user + "&pw=" + pass,
                type: "Get",
                success: function (data) {
                    if (data != "") {
                        TK = data;
                        alert("Welcom " + data.UserName);
                    }
                    else
                        alert("UserName Hoac Password Khong Dung");

                },
                error: function () {
                    alert('Failure ');
                }
            });
        }
    }
}


//////////////////////////////////////////////////////
// Đăng xuất...
//////////////////////////////////////////////////////
function btnLogout_Click() {
    alert("Đăng xuất...");
    TK = emptyJson;
}


//////////////////////////////////////////////////////
// Đăng ký...
//////////////////////////////////////////////////////
function btnRegister_Click() {
    myWindow = window.open('', '', 'width=400,height=250');
    myWindow.document.write(
    '<head>' +
                '<title>REGISTER ACCOUNT</title>' +
                    ' <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>' +
                   '<script src="Scripts/mapsextend.js" type="text/javascript"></script>' +

'</head>' +
'<body>' +
    '<table style="width:300px;">' +
        '<tr>' +
            '<td colspan="2" align="center">' +
                'REGISTER ACCOUNT&nbsp;</td>' +
        '</tr>' +
        '<tr>' +
            '<td align="right" style="width: 40%">' +
                '<Label ID="Label1">Username: </Label>' +
            '</td>' +
            '<td style="width: 60%">' +
                '<input id="txt_user" type="text" align="left" />' +
            '</td>' +
        '</tr>' +
        '<tr>' +
            '<td align="right" style="width: 40%">' +
                '<Label ID="Label2">Password: </Label>' +
            '</td>' +
            '<td style="width: 60%">' +
                '<input id="txt_pass" type="password" />' +
            '</td>' +
        '</tr>' +
                '<tr>' +
            '<td align="right" style="width: 40%">' +
                '<Label ID="lbCfirm">Comfirm Password: </Label>' +
            '</td>' +
            '<td style="width: 60%">' +
                '<input id="txt_comfirmpass" type="password" />' +
            '</td>' +
        '</tr>' +

        '<tr>' +
            '<td align="center" colspan="2">' +
                '<input id="Button1" type="button" value="Register" onclick="btn_DangKy()"/>' +
                    '&nbsp;&nbsp;' +
                '<input id="Button2" type="button" value="Close" onclick="btn_Thoat()"/>' +
            '</td>' +
        '</tr>' +
    '</table>' +
    '</body>');
    myWindow.focus();
}


//////////////////////////////////////////////////////
// Hàm xử lý đăng ký...
//////////////////////////////////////////////////////
function btn_DangKy() {
    var user = document.getElementById("txt_user").value;
    var pass = document.getElementById("txt_pass").value;
    var cpass = document.getElementById("txt_comfirmpass").value;
    if (cpass != pass) {
        alert("Mat Khau Khong Trung Nhau");
        return;
    }
    if (user == "") {
        alert("Ban chua nhap user!...");
        return;
    }
    else {
        if (pass == "") {
            alert("Ban chua nhap pass!...");
            return;
        }
        else if (ktTaiKhoan(user) == false) {
            alert("Tai Khoan Da Ton Tai");
            return;
        }
        else {
            // Viết hàm đăng ký tài khoản...
            // alert("Ban da dang ky!...");
            var tk = {};
            tk.UserName = user;
            tk.PassWord = pass;
            tk.Email = "";
            $.ajax({
                cache: false,
                async: false,
                url: "http://localhost:8989/Map/TK",
                type: "POST",
                data: JSON.stringify(tk),
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                success: function (data) {
                    alert('Successful');
                },
                error: function () {
                    alert('Failure');
                }
            });
            window.close();
        }
    }
}


//////////////////////////////////////////////////////
function ktTaiKhoan(user) {
    var res;
    $.ajax({
        cache: false,
        async: false,
        url: "http://localhost:8989/Map/getContactsFromUserName?user_name=" + user,
        type: "Get",
        success: function (data) {
            res = data;
        },
        error: function () {
            alert('Failure ');
        }
    });
    return res;
}


//////////////////////////////////////////////////////
// Hàm xử lý thoát...
//////////////////////////////////////////////////////
function btn_Thoat() {
    alert("Ban da thoat!");
    window.close();
}


//////////////////////////Add Contact/////////////////////////////////
function btnAddContact_Click() {
    if (TK.ID == null) {
        alert("Ban Chua Dang Nhap");
        return;
    }
    myWindow = window.open('', '', 'width=400,height=250');
    myWindow.document.write(
    '<head>' +
                '<title>AddContact</title>' +
                   ' <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>' +
                    '<script src="Scripts/mapsextend.js" type="text/javascript"></script>' +

'</head>' +
'<body>' +
   ' <form id="form1" >' +
    '<div>' +
        "<fieldset>" +
            '<legend>Add New Contact</legend>' +
            '<table>' +
             '   <tr>' +
                    '<td>' +
                        '<label id="lbAddContact">' +
                            'UserName</label>' +
                    '</td>' +
                    '<td>' +
                        '<input id="txt_UserName"  type="text"  />' +
                    '</td>' +
                    '<td>' +

                            '<a  href="javascript:void(0);" name="' + TK.ID +
                       '" onclick="btn_Add_Click(this);">Add</a>' +
                    '</td>' +
                         '<td>' +
                        '<input id="btn_Close"  type="button" value="Close"  onclick="btn_Close_Click()"/>' +
                    '</td>' +
                '</tr>' +
            '</table>' +
        '</fieldset>' +
    '</div>' +
    '</form>' +
'</body> ');
    myWindow.focus();
}


//////////////////////////////////////////////////////
function btn_Add_Click(link) {
//    alert(link.name);
    var contact_name = document.getElementById("txt_UserName").value;
    if (contact_name == "") {
        alert("Chua Nhap Contact Name");
        return;
    }

    $.ajax({
        cache: false,
        async: false,
        url: "http://localhost:8989/Map/AddNewContact?id_user=" + link.name + "&contact_name=" + contact_name,
        type: "POST",
        //            data: JSON.stringify(tk),
        contentType: "application/json; charset=utf-8",
        //            dataType: 'json',
        success: function (data) {
//            alert(data);
        },
        error: function () {
            alert('Failure ');
        }
    });

}


//////////////////////////////////////////////////////
$(document).ready(function () {
    //sự kiện nhấn vào nut Add Contack
    $("#btn_AddContact").click(function () {
        btnAddContact_Click();
    });
});
function ShareDiaDiem(link) {
    var id_didiem = link.name;
    directToShareWindow(TK.ID, id_didiem);
}
function directToShareWindow(id_user, id_didiem) {
    var string_option = generateOption(id_user);
    myWindow = window.open('', '', 'width=400,height=250');
    myWindow.document.write(
    '<head>' +
                '<title>AddContact</title>' +
                   ' <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>' +
                    '<script src="Scripts/mapsextend.js" type="text/javascript"></script>' +
'</head>' +
'<body>' +
   ' <form id="form1" >' +
    '<div>' +
        "<fieldset>" +
            '<legend>Hay Chia Se Dia Diem Voi Ban Ba</legend>' +
            '<table>' +
             '   <tr>' +
                    '<td>' +
                        '<label id="Contacts">' +
                            'Contacts</label>' +
                    '</td>' +
                    '<td>' +
                        '<select id="list_contacts"  />' + string_option +
                        '</select>' +
                    '</td>' +
                    '<td>' +
                         '<a  href="javascript:void(0);" name="' + id_didiem +
                       '" onclick="btn_Share_Click(this);">Share</a>' +
                    '</td>' +
                   ' <td><input id="btn_Close" type="button" value="Close" onclick="btn_Close_Click()"></td>' +
                '</tr>' +
            '</table>' +
        '</fieldset>' +
    '</div>' +
    '</form>' +
'</body> ');
    myWindow.focus();
}


//////////////////////////////////////////////////////
function btn_Close_Click() {
    window.close();
}


//////////////////////////////////////////////////////
function generateOption(id_user) {
    var res = "";
    $.ajax({
        cache: false,
        async: false,
        url: "http://localhost:8989/Map/getContacts?id_user=" + id_user,
        type: "Get",
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                res += '<option value=' + data[i].ID + '>' + data[i].UserName + '</option>';
            }
        },
        error: function () {
            alert('Failure ');
        }
    });
    return res;
}


//////////////////////////////////////////////////////
function btn_Share_Click(link) {
    var id_contact = document.getElementById('list_contacts').value;
//    alert(id_contact.toString());
    var id_diadiem = link.name;
    $.ajax({
        cache: false,
        async: false,
        url: "http://localhost:8989/Map/ShareDiaDiem?id_user=" + id_contact + "&id_diadiem=" + id_diadiem,
        type: "POST",
        //            data: JSON.stringify(tk),
        contentType: "application/json; charset=utf-8",
        //            dataType: 'json',
        success: function (data) {
            alert("Share Thanh Cong");
        },
        error: function () {
            alert('Failure ');
        }
    });

}














